/******************************************************************************
 * Copyright 2011 Berner New Media (http://annonse.db.no/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

/******************************************************************************
 *
 * INTERSTITIAL OVERLAY OBJECT
 *
 * DEPENDANCY:
 * * JQuery 1.6.2
 *
 * TODO
 * *
 *
 ******************************************************************************/
var interstitialObject = function(config) {
    var _root = this,
        settings = {
            content: {
                creative: false,
                width: $(document).width(),
                height: $(document).height()
            },
            wallpaper: {
                creative: false,
                width: $(document).width(),
                height: $(document).height()
            },
            navigation: {
                menu: true,
                title: "<a href='http://annonseinfo.dagbladet.no/' target='_blank'>Annonse</a>",
                buttontext: "Fortsett til " + location.host,
                removeTimeMs: 400
            },
            maxSafeWidth: 1024,
            autoPosition: true,
            closeCallback: function() {
                return null;
            }
        },
        $overlay,
        $contentContainer,
        $contentWrapper,
        $wallpaper,
        $wallpaperWrapper,
        $menuContainer,
        $menu,
        $logo,
        $title;

    var prepearConfig = function() {
            $.extend(true, settings, config);
            if (settings.maxSafeWidth) {
                if (settings.content.width > settings.maxSafeWidth) {
                    settings.content.width = settings.maxSafeWidth;
                }
                if (settings.wallpaper.width > settings.maxSafeWidth) {
                    settings.wallpaper.width = settings.maxSafeWidth;
                }
            }
        },
        returnIframeFromDataset = function(creativeDataset) {
            var $iframe = $("<iframe/>");
            $iframe.attr({
                src: creativeDataset.creative,
                width: "100%",
                height: creativeDataset.height,
                frameborder: 0,
                allowtransparency: "true",
                scrolling: "no",
				marginwidth: 0,
				marginheight: 0
            });
            $iframe.css({
                "background": "transparent"
            });
            return $iframe;
        },
        isUrl = function(subject) {
            if (typeof(subject) == "string") {
                var url_pattern = new RegExp("((http|https)(:\/\/))?([a-zA-Z0-9-_]+[.]{1}){2}[a-zA-z0-9-_]+(\/{1}[a-zA-Z0-9-_]+)*\/?", "i");
                return subject.match(url_pattern);
            }
            else {
                return false;
            }
        },
        createAndAppendOverlay = function() {
            $overlay = $("<div/>");
            $overlay.attr("id", "interstitial-ad");
            $overlay.css({
                "width": "100%",
                "height": "100%",
                "position": "fixed",
                "top": 0,
                "z-index": 999999
            });
            $("body").prepend($overlay);
        },
        createAndAppendWallpaper = function() {
            $wallpaperWrapper = $("<div/>");
            $wallpaperWrapper.attr("id", "wallpaper-wrapper");
            $wallpaperWrapper.css({
                "width": settings.wallpaper.width,
                "position": "relative",
                "overflow": "hidden"
            });
            $wallpaperWrapper.click(function(e) {
                e.stopPropagation();
            });
            if (isUrl(settings.wallpaper.creative)) {
                settings.wallpaper.creative = returnIframeFromDataset(settings.wallpaper);
            }
            $wallpaper = $(settings.wallpaper.creative);
            $wallpaperWrapper.append($wallpaper);
            $contentContainer.prepend($wallpaperWrapper);
        },
        createAndAppendContent = function() {
            $contentContainer = $("<div/>");
            $contentContainer.attr({
                id: "content-container"
            });
            $contentContainer.css({
                "height": "100%",
                "position": "relative",
                "overflow": "hidden"
            });
            $contentContainer.click(function(event) {
                _root.remove();
            });
            if (isUrl(settings.content.creative)) {
                settings.content.creative = returnIframeFromDataset(settings.content);
            }
            $content = $(settings.content.creative);
            $contentWrapper = $("<div/>");
            $contentWrapper.attr({
                id: "content-wapper"
            });
            $contentWrapper.css({
                "width": settings.content.width,
                "position": "absolute",
                "overflow": "hidden",
                "top": 0
            });
            $contentWrapper.click(function(e) {
                e.stopPropagation();
            });
            $contentWrapper.append($content);
            $contentContainer.append($contentWrapper);
            $overlay.append($contentContainer);
        },
        disableScroll = function() {
            $("body").css({
                overflow: "hidden"
            });
        },
        enableScroll = function() {
            $("body").css({
                height: "auto",
                overflow: "auto"
            });
        },
        createAndAppendMenu = function() {
            $menuContainer = $("<div/>");
            $menuContainer.attr({
                id: "navigation-container"
            });
            $menuContainer.css({
                "position": "relative",
                "z-index": 1
            });
            $title = $("<span/>");
            $title.addClass("title");
            $title.html(settings.navigation.title);
            $menu = $("<div/>");
            $menu.append($title);
            $menu.addClass("navigation");
            $logo = $("<div/>");
            $logo.addClass("logo");
            $logo.click(function(){
                _root.remove();
            });
            $closeButton = $("<input/>");
            $closeButton.attr({
                type: "button",
                value: settings.navigation.buttontext
            });
            $closeButton.click(function(event) {
                _root.remove();
            });
            $closeButton.hover(
                function() {
                    $(this).addClass("hover");
                }, function() {
                    $(this).removeClass("hover");
                }
            );
            $menu.append($closeButton);
            $menuContainer.append($logo);
            $menuContainer.append($menu);
            $overlay.append($menuContainer);
        },
        centerElement = function($elm) {
            var windowWidth = $(window).width(),
                elementWidth = $elm.width();
            $elm.css("left", (windowWidth - elementWidth) / 2);
        },
        initialize = function() {
            prepearConfig();
            if (!settings.content.creative && console.warn) {
                console.warn(""
                    + "No Creative Set.\n"
                    + "Please pass creative as constructor when calling Interstial Object:\n"
                    + "new interstitalObject\n"
                    + "({\n"
                    + "\tcreative :\n"
                    + "\t{\n"
                    + "\t\tcontent : 'URL, string or JQObject'\n"
                    + "\t}\n"
                    + "});"
                );
                return false;
            }
            else {
                disableScroll();
                createAndAppendOverlay();
                if (settings.navigation.menu) {
                    createAndAppendMenu();
                }
                createAndAppendContent();
                if (settings.autoPosition) {
                    centerElement($contentWrapper);
                }
                if (settings.wallpaper.creative) {
                    createAndAppendWallpaper();
                    if (settings.autoPosition) {
                        centerElement($wallpaperWrapper);
                    }
                }
                if (settings.autoPosition) {
                    $(window).resize(function() {
                        centerElement($contentWrapper);
                        if (settings.wallpaper.creative) {
                            centerElement($wallpaperWrapper);
                        }
                    });
                }
            }
        };
    this.remove = function() {
        var removeQueue = $({});
        if (typeof(settings.closeCallback) == "function") {
            removeQueue.queue("notAuto", function(dequeueEvent) {
                settings.closeCallback();
                dequeueEvent();
            });
        }
        removeQueue.queue("notAuto", function(dequeueEvent) {
            $contentContainer.empty();
            dequeueEvent();
        });
        if (settings.navigation.menu) {
            removeQueue.queue("notAuto", function(dequeueEvent) {
                $contentContainer.fadeOut(settings.navigation.removeTimeMs);
                $menuContainer.animate({
                    top: -$menuContainer.outerHeight()
                },
                settings.navigation.removeTimeMs,
                function() {
                    dequeueEvent();
                });
            });
        } else {
            removeQueue.queue("notAuto", function(dequeueEvent) {
                $contentContainer.fadeOut(200, function() {
                    dequeueEvent();
                });
            });
        }
        removeQueue.queue("notAuto", function(dequeueEvent) {
            $overlay.remove();
            dequeueEvent();
        });
        removeQueue.queue("notAuto", function(dequeueEvent) {
            enableScroll();
            dequeueEvent();
        });
        removeQueue.dequeue("notAuto");
    };
    initialize();
};